package org.example.core.schedule;

import org.example.base.common.model.TDatabaseBackModel;
import org.example.base.common.service.TDatabaseBackService;
import org.example.core.exception.ErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.SimpleDateFormat;

/**
 * Description: 数据库备份定时任务
 * Date: 2024/2/10 20:15
 */
@Component
public class DatabaseBackSchedule {

    @Value("${common.mysql.path}")
    private String mysqlPath;

    @Value("${common.mysql.username}")
    private String username;

    @Value("${common.mysql.password}")
    private String password;

    @Value("${common.mysql.name}")
    private String dbName;

    @Value("${file.path}")
    private String filePath;

    @Autowired
    private TDatabaseBackService tDatabaseBackService;

    /**
     * 凌晨一点备份
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void databaseBack() {
        ProcessBuilder processBuilder = new ProcessBuilder(mysqlPath + "mysqldump",
                "--user=" + username,
                "--password=" + password,
                dbName);
        try {
            SimpleDateFormat format = new SimpleDateFormat("YYYYMMDDHHmmss");
            String fileName = format.format(System.currentTimeMillis());
            String fileLocation = fileName + ".sql";
            File file = new File(filePath + "mysql_back/", fileLocation);
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdir();
            }
            //判断是否存在该文件
            if (!file.exists()) {
                file.createNewFile();
            }
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
            String line;
            while ((line = reader.readLine()) != null) {
                writer.write(line);
                System.out.println(line);
            }
            writer.flush();
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                TDatabaseBackModel databaseBackModel = new TDatabaseBackModel();
                databaseBackModel.setName(fileName);
                databaseBackModel.setLocation("mysql_back/" + fileLocation);
                tDatabaseBackService.add(databaseBackModel);
                System.out.println("数据备份成功！");
            } else {
                System.out.println("数据备份失败！");
            }

        } catch (Exception e) {
            throw new ErrorException(e);
        }

    }
}
